package com.vvv.shortlink.project.service.impl;

import com.vvv.shortlink.project.service.UrlTitleService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URL;

import static com.vvv.shortlink.project.constant.LinkConstant.HTTP_TIMEOUT;


@Service
@Slf4j
public class UrlTitleServiceImpl implements UrlTitleService {


    @Override
    public String getTitleByUrl(String url) {
        try {
            Document document = Jsoup.connect(url).timeout(HTTP_TIMEOUT).get();
            String title = document.title();
            if (title == null || title.isEmpty()) {
                return new URL(url).getHost(); // 如果标题为空，则返回域名
            }
            return title;
        } catch (HttpStatusException e) {
            log.error("获取URL时接收到HTTP错误: {} - 错误码: {}", url, e.getStatusCode());
        } catch (MalformedURLException e) {
            log.error("URL格式错误: {}", url, e);
        } catch (Exception e) {
            log.error("获取URL标题时出错: {}", url, e);
        }
        try {
            return new URL(url).getHost(); // 在其他异常情况下也返回域名
        } catch (MalformedURLException e) {
            log.error("提取域名时URL格式错误: {}", url, e);
            return ""; // 如果URL格式不正确，则无法提取域名，返回空字符串
        }
    }
}
